package cn.study.luckyinfrastructure.gateway.iml;

import cm.study.config.enums.LdExeceptionEnum;
import cm.study.config.util.AssertUtil;
import cn.study.luckyclient.dto.query.RuleListByParamQuery;
import cn.study.luckydomain.gateway.RuleGateway;
import cn.study.luckydomain.rule.RuleEntity;
import cn.study.luckyinfrastructure.convertor.RuleConvertor;
import cn.study.luckyinfrastructure.gateway.iml.dataObject.RuleDB;
import cn.study.luckyinfrastructure.gateway.iml.mapper.RuleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@AllArgsConstructor
public class RuleGatewayImpl implements RuleGateway {
    private final RuleMapper ruleMapper;
    @Override
    public RuleEntity add(RuleEntity rule) {
        RuleDB ruleDB = RuleConvertor.toRuleDB(rule);
        int insert = ruleMapper.insert(ruleDB);
        AssertUtil.isTrue(insert<1, LdExeceptionEnum.ADD_ERROR.getDescription());
        return RuleConvertor.toEntity(ruleDB);
    }

    @Override
    public RuleEntity update(RuleEntity rule) {
        RuleDB ruleDB = RuleConvertor.toRuleDB(rule);
        QueryWrapper<RuleDB> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("id",ruleDB.getId());
        int update = ruleMapper.update(ruleDB, objectQueryWrapper);
        AssertUtil.isTrue(update<1, LdExeceptionEnum.UPDATE_ERROR.getDescription());
        return RuleConvertor.toEntity(ruleDB);
    }

    @Override
    public IPage<RuleEntity> query(RuleListByParamQuery rule) {
        IPage<RuleDB> page=new Page<>();
        LambdaQueryWrapper<RuleDB> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(rule.getRuleName()!=null,RuleDB::getRuleName,rule.getRuleName());
        lambdaQueryWrapper.in(rule.getId()!=null,RuleDB::getId,rule.getId());
        if(Objects.nonNull(rule.getIds())){
            List<Long> ids = rule.getIds();
            for(Long id:ids){
                lambdaQueryWrapper.in(RuleDB::getId,id);
            }
        }
        IPage<RuleDB> page1 = ruleMapper.selectPage(page, lambdaQueryWrapper);
        return page1.convert(RuleConvertor::toEntity);
    }
}
